import {Component, OnInit} from '@angular/core';
import {BsModalRef} from 'ngx-bootstrap';
import {User} from '../user.model';
import {UserService} from "../user.service";

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html'
})
export class UserEditComponent implements OnInit {
  title: string;
  isCancel: boolean = true;
  user: User;
  isAdd: boolean;
  confirmValue: string;

  errorMsg: string;

  isNameError: boolean = false;

  nameErrorMsg: string;

  isConfirm: boolean = true;

  constructor(public bsModalRef: BsModalRef, private userService: UserService) {
  }

  ngOnInit() {
  }

  btnCloseClick() {
    this.bsModalRef.hide();
  }

  btnConfirmClick() {
    if (!this.isAdd || (this.isConfirm && !this.errorMsg && !this.isNameError)) {
      this.isCancel = false;
      this.bsModalRef.hide();
    }
  }

  statusChange(a: boolean) {
    if (a) {
      this.user.status = 1;
    } else {
      this.user.status = 0;
    }
  }

  checkName() {
    if (this.user.name == null) {
      this.isNameError = true;
      this.nameErrorMsg = '用户名不能为空';
    } else {
      this.userService.checkName(this.user.name).then(data => {
        if (data['success']) {
          this.isNameError = !data['data'];
          if (this.isNameError) {
            this.nameErrorMsg = '用户已存在';
          }
        } else {
          this.errorMsg = data['errorMsg']
        }
      })
    }
  }

  confirmPasswd() {
    this.isConfirm = this.user.password === this.confirmValue;
  }

}
